#include <iostream>
#include <string>
#include <cstring>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include "netaddr.hpp"
using namespace std;

int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        cout << "Incorrect use, correct use :" << endl
             << "        ./server local_ip local_port" << endl;
        return 1;
    }

    // 初始化服务端套接字
    string ip = argv[1];
    uint16_t port = stoi(argv[2]);
    // 网络文件信息
    int sockfd = socket(AF_INET, SOCK_STREAM, 0);

    // 需要bind 但是仍然不是显式的bind，而是在connect时连接
    struct sockaddr_in addr;
    memset(&addr, 0, sizeof(addr));
    addr.sin_family = AF_INET;
    inet_pton(AF_INET, ip.c_str(), &addr.sin_addr);
    addr.sin_port = htons(port);

    int n = connect(sockfd, (struct sockaddr *)&addr, sizeof(addr));
    if (n < 0)
    {
        exit(1);
    }

    while (true)
    {
        string buffer;
        char readbuffer[4096];
        cout << "Please Enter# ";
        getline(cin, buffer);
        ssize_t n = write(sockfd, buffer.c_str(), buffer.size());
        if (n < 0)
        {
            exit(2);
        }
        else
        {
            n = read(sockfd, readbuffer, sizeof(readbuffer) - 1);
            if (n == 0)
            {
                cout << "server quit" << endl;
                break;
            }
            else if (n < 0)
                exit(2);
            else
            {
                readbuffer[n] = 0;
                cout << "server say# " << readbuffer << endl;
            }
        }
    }

    return 0;
}
